 package fr.doume.jna.sspi;

//tomcat 5.5
//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;

//tomcat 6
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;

import fr.doume.jna.jna.Sspibis.CtxtHandle;
import fr.doume.jna.jna.Sspibis.CredHandle;
import fr.doume.jna.jna.Secur32bis;
import java.io.Serializable;

public class WindowsContext implements Serializable

{
  protected long dwUpperCredential = 0;
  protected long dwLowerCredential = 0;
  protected long dwUpperContext = 0;
  protected long dwLowerContext = 0; 
  
 	private static Log log = LogFactory.getLog(WindowsContext.class);

  public WindowsContext()
  {
    this(0L,0L,0L,0L);
  }

  public WindowsContext(long dwlowercred, long dwuppercred, long dwlowerctx, long dwupperctx)
  {
    dwLowerCredential = dwlowercred;
    dwUpperCredential = dwuppercred;
    dwLowerContext = dwlowerctx;
    dwUpperContext = dwupperctx;
    if (log.isDebugEnabled())
    {
      log.debug ("****************************************!!!New WindowsContext");
      log.debug(
        "dwLowerCredential: " + dwLowerCredential +" ,dwUpperCredential: " + dwUpperCredential +
        " , dwLowerContext: " + dwLowerContext +" ,dwUpperContext: " + dwUpperContext);
    }
  }
  
  protected void finalize()
	{
    if ( ! isContextInvalid() )
    {
      if (log.isDebugEnabled())
      {
        log.debug("finalize: valid context");
        log.debug("dwLowerContext: " + dwLowerContext +" ,dwUpperContext: " + dwUpperContext);
      }
      CtxtHandle hContext = new CtxtHandle( dwLowerContext, dwUpperContext); 
      Secur32bis.INSTANCE.DeleteSecurityContext(hContext);
      dwLowerContext = 0;
      dwUpperContext = 0;
      hContext.dwLower.setValue(0);
      hContext.dwUpper.setValue(0);

    }
    if (  ! isCredentialInvalid() )
    {
      if (log.isDebugEnabled())
      {
        log.debug("finalize: valid credential");
        log.debug("dwLowerCredential: " + dwLowerCredential +" ,dwUpperCredential: " + dwUpperCredential );
      }

      CredHandle hCredential = new CredHandle( dwLowerCredential, dwUpperCredential); 
      Secur32bis.INSTANCE.FreeCredentialsHandle(hCredential);
      dwLowerCredential = 0;
      dwUpperCredential = 0;
      hCredential.dwLower.setValue(0);
      hCredential.dwUpper.setValue(0);
    }
  }
  
  private boolean isContextInvalid()
  {
    return ( ( dwUpperContext == 0  && dwLowerContext ==0 )  || ( dwUpperContext == -1 && dwLowerContext == -1) );
  }
  
  private boolean isCredentialInvalid()
  {
    return ( ( dwUpperCredential == 0  && dwLowerCredential ==0 ) || (dwUpperCredential == -1 && dwLowerCredential == -1) );
  }

}
